package com.haiyou.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.haiyou.common.constant.MessageCode;
import com.haiyou.common.exception.BusinessException;
import com.haiyou.common.response.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Map;

/**
 * @author chenzeke
 * @date 2018/12/6 18:15
 */
@ControllerAdvice
@Slf4j
public class CommonExceptionHandler {
    /**
     * 全局异常捕捉处理
     *
     * @param e 通用异常
     * @return ResponseResult
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ResponseResult exceptionHandler(Exception e, HttpServletRequest request) {
        httpLog(request);
        log.error(e.getMessage(), e);
        return ResponseResult.error(MessageCode.FORM_ERROR, e.getMessage());
    }

    /**
     * 全局运行异常
     *
     * @param e 运行异常
     * @return ResponseResult
     */
    @ResponseBody
    @ExceptionHandler(value = RuntimeException.class)
    public ResponseResult exceptionHandler(RuntimeException e) {
        log.error(e.getMessage(), e);
        return ResponseResult.error(MessageCode.FORM_ERROR, e.getMessage());
    }

    /**
     * 业务处理类型异常
     *
     * @param e 业务异常
     * @return ResponseResult
     */
    @ResponseBody
    @ExceptionHandler(value = BusinessException.class)
    public ResponseResult hqImExceptionHandler(BusinessException e) {
        log.error(e.getMessage(), e);
        return ResponseResult.error(e.getCode(), e.getMessage(), e.getData());
    }

    /**
     * 表单验证异常捕获
     *
     * @param e 表单验证异常
     * @return ResponseResult
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public ResponseResult jsonBindExceptionHandler(BindException e) {
        log.info(e.getMessage(), e);
        return ResponseResult.error(MessageCode.FORM_ERROR, e.getMessage());
    }

    /**
     * 打印http请求日记
     *
     * @param request
     */
    private void httpLog(HttpServletRequest request) {
        JSONObject header = new JSONObject();
        Enumeration names = request.getHeaderNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            header.put(name, request.getHeader(name));
        }
        log.error("header===>[{}]" + header);
        JSONObject data = new JSONObject();
        Map<String, String[]> parameterMap = request.getParameterMap();
        data.put("parameterMap", parameterMap);
        data.put("url", request.getRequestURI());
        data.put("method", request.getMethod());
        log.error("data===>[{}]", data);
    }

}
